package com.simteek.testspringdata.controller;

import com.simteek.testspringdata.entity.User;
import com.simteek.testspringdata.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/demo")
    @ResponseBody
    public Map demo(HttpServletResponse response, String arg) {
        Map map = new HashMap();
        map.put("result", arg);
        return map;
    }

    @RequestMapping(value = "/save")
    @ResponseBody
    public Map save(HttpServletResponse response, Integer age, String firstName, String lastName) {
        Map map = new HashMap();
        try {
            User user = userService.save(age, firstName, lastName);
            map.put("result", user.get_id());
        } catch (Exception e) {
            e.printStackTrace();
            map.put("result", false);
        }
        return map;
    }

    @RequestMapping(value = "/findAll")
    @ResponseBody
    public Map findAll(HttpServletResponse response) {
        Map map = new HashMap();
        List list = userService.findAll();
        map.put("result", list);
        return map;
    }

    @RequestMapping(value = "/findBy")
    @ResponseBody
    public Map findByFirstName(HttpServletResponse response, String by, String value) {
        Map map = new HashMap();
        List list = userService.findBy(by, value);
        map.put("result", list);
        return map;
    }

    @RequestMapping(value = "/deleteById")
    @ResponseBody
    public Map deleteById(HttpServletResponse response, String _id) {
        Map map = new HashMap();
        userService.deleteById(_id);
        map.put("result", true);
        return map;
    }


}
